package stack_quene.stack.stack;

import java.util.Arrays;
import java.util.NoSuchElementException;

public class Stack<E> {
    public boolean isEmpty;
    private E[] elementdata;
    private int size;

    public Stack() {
        elementdata = (E[]) new Object[10];
    }

    public Stack(int initCap) {
        elementdata = (E[]) new Object[initCap];
    }

    //入栈操作
    public void push(E value) {
        //扩容
        if (size == elementdata.length) {
            grow();
        }
        elementdata[size] = value;
        size++;
    }

    //出栈操作
    public E pop() {
        if (getSize() == 0) {
            throw new NoSuchElementException("栈为空");
        }
        E oldValue = elementdata[size - 1];
        size--;
        elementdata[size] = null;
        return oldValue;

    }

    //查看栈顶元素但不删除
    public E peek() {
        if (getSize() == 0) {
            throw new NoSuchElementException("栈为空");
        }
        return elementdata[size - 1];

    }

    public int getSize() {
        return size;

    }

    //扩容操作
    public void grow() {
        int oldValue = this.elementdata.length;
        int newValue = oldValue << 1;
        this.elementdata = Arrays.copyOf(elementdata, newValue);
    }


    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder();
        sb.append("[");
        for (int i = 0; i < size; i++) {
            sb.append(elementdata[i]);
            if(i!=size-1){
                sb.append(",");
            }
        }
         sb.append("] top");
        return sb.toString();
    }

    public boolean isEmpty() {
        return false;
    }
}
